﻿using IcicleFramework.Components;
using IcicleFramework.Components.Metadata;
using IcicleFramework.Components.Movement;
using IcicleFramework.Components.Physics;
using IcicleFramework.Inputs;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace ExampleGame.Components.Movement
{
    public class PlayerBaseMovementComponent : BaseMovementComponent
    {
        protected IPhysicsComponent physicsComponent;

        public Player Player { get; set; }

        public PlayerBaseMovementComponent()
            : base()
        {}
        
        protected PlayerBaseMovementComponent(PlayerBaseMovementComponent old)
            :base(old)
        {
            this.Player = old.Player;
        }


        public override void Update(GameTime gameTime)
        {
            Vector2 impulse = Vector2.Zero;
            Vector2 actualSpeed = MaxVelocity * (float) gameTime.ElapsedGameTime.TotalSeconds;

            if (physicsComponent != null && Player != null)
            {
                if (Player.InputHandler.IsDown(Buttons.DPadUp, Player.Controller) ||
                    Player.InputHandler.IsDown(Keys.Up))
                {
                    impulse.Y = -actualSpeed.Y;
                }
                if (Player.InputHandler.IsDown(Buttons.DPadDown, Player.Controller) ||
                    Player.InputHandler.IsDown(Keys.Down))
                {
                    impulse.Y = actualSpeed.Y;
                }

                if (Player.InputHandler.IsDown(Buttons.DPadLeft, Player.Controller) ||
                    Player.InputHandler.IsDown(Keys.Left))
                {
                    impulse.X = -actualSpeed.X;
                }
                if (Player.InputHandler.IsDown(Buttons.DPadRight, Player.Controller) ||
                    Player.InputHandler.IsDown(Keys.Right))
                {
                    impulse.X = actualSpeed.X;
                }

                physicsComponent.ApplyImpulse(impulse);
            }

            base.Update(gameTime);
        }

        public override void Initialize()
        {
            //Try to find the Metadata component and pull player information from it.
            IMetadataComponent metadataComponent = Parent.GetComponent<IMetadataComponent>();

            if (metadataComponent != null)
            {
                Player player = metadataComponent.GetMetadata("player") as Player;

                if (player != null)
                    this.Player = player;
            }

            //We need a physics component -- hope we have one!
            physicsComponent = Parent.GetComponent<IPhysicsComponent>();

            base.Initialize();
        }

        public override IBaseComponent DeepClone()
        {
            return new PlayerBaseMovementComponent(this);
        }
    }
}
